package com.mmp.main.endpoints;

import java.io.IOException;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.SpringConfigurator;

import com.mmp.common.util.Common;
import com.mmp.main.DB.DBQueryManager;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

@Component
@ServerEndpoint(value = "/JobOrdersNotifier", configurator = SpringConfigurator.class)
public class JobOrderNotificationsEndPoint {

	@Autowired
	DBQueryManager dbQueryManager;

	private static final Logger LOGGER = Logger
			.getLogger(JobOrderNotificationsEndPoint.class.getName());
	private static Queue<Session> queue = new ConcurrentLinkedQueue<>();

	@OnOpen
	public void onOpen(Session session) {
		queue.add(session);
		sendMessage(session,
				getNotification(WebUtil.getSiteIdFromEndPointSession(session)));
		LOGGER.log(Level.INFO, "New connection with client: {0}",
				session.getId());
		Common.log("Number of opened connections is ************** "
				+ queue.size());
	}

	@OnClose
	public void onClose(Session session) {
		queue.remove(session);
		LOGGER.log(Level.INFO, "Close connection for client: {0}",
				session.getId());
		Common.log("Number of opened connections is ************** "
				+ queue.size());
	}

	@OnError
	public void onError(Throwable exception, Session session) {
		queue.remove(session);
		exception.printStackTrace();
		LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
	}

	/*
	 * 
	 * @OnMessage public String onMessage(String message, Session session) { try
	 * { session.getBasicRemote().sendText(
	 * "hello world ! notifications websocket works fine"); } catch (IOException
	 * e) { Common.log(e); } return "Server received [" + message + "]"; }
	 */

	public void broadcastNotificationUpdates(Integer siteId) {
		String message = getNotification(siteId);
		try {
			for (Session s : queue) {
				if (siteId == WebUtil.getSiteIdFromEndPointSession(s))
					sendMessage(s, message);
				// LOGGER.log(Level.INFO, "Broadcasting Notification Updates:" +
				// s.getId(), message);
			}
		} catch (Exception e) {
			Common.log(e);
		}

	}

	private static void sendMessage(Session session, String msg) {
		try {
			if (session != null && session.isOpen())
				session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			Common.log(e);
		}
	}

	private String getNotification(Integer siteId) {
		if (siteId == null || siteId == 0)
			return "";

		List<JobOrder> list = dbQueryManager.getJobOrders(siteId, 0, 0, 0,
				Enums.JOB_ORDER_STATUS.LATE);
		if (list == null || list.isEmpty())
			return "";

		String notfHtml = "<div id='jo_notifications_ph'><img src='image/warning.png' />"
				+ "يوجد أوامر عمل تحتاج متابعة .. "
				+ "<a href='ViewLateJobOrders' target='_blank'>التفاصيل</a>"
				+ "<a title='تجاهل هذا التنبيه' class='close_btn' href='javascript:void(0)' onclick=\"activateNotificationStopperCookie(this,'stop_jo_notify')\">X</a>";

		return notfHtml + "</div>";
	}

	/*
	 * private String getNotification() { List<JobOrder> list =
	 * getLateJobOrdersForNotifications(); if (list == null || list.isEmpty())
	 * return "";
	 * 
	 * String qStrFirstPart = Default.SEARCH_DEST_PARAM_NAME + "=" +
	 * Default.SEARCH_DEST_FOLLOWUP_JOB_OREDR_PARAM_VALUE;
	 * 
	 * String notfHtml = "<div><img src='image/warning.png' />" +
	 * "يوجد أوامر عمل تحتاج متابعة وأرقامها هي : " +
	 * "<a href='SearchForJobOrderProcess?" + qStrFirstPart + "&jobOrderNo=" +
	 * list.get(0).getJobOrderNo() + "'>" + list.get(0).getJobOrderNo() +
	 * "</a>"; for (int i = 1; i < list.size(); i++) notfHtml += " , " +
	 * "<a target='_blank' href='SearchForJobOrderProcess?" + qStrFirstPart +
	 * "&jobOrderNo=" + list.get(i).getJobOrderNo() + "'>" +
	 * list.get(i).getJobOrderNo() + "</a>";
	 * 
	 * return notfHtml + "</div>";
	 * 
	 * }
	 */
}
